// JSON Formatter 渲染器
window.JSONFormatterRenderer = class JSONFormatterRenderer {
    static getHTML() {
        return `
            <div class="flex items-center justify-between mb-6">
                <h2 class="text-3xl font-bold text-gray-800">JSON 工具箱</h2>
                <div class="flex items-center space-x-4">
                    <div class="text-sm text-gray-500">
                        <span id="json-status" class="font-medium">就绪</span>
                    </div>
                </div>
            </div>

            <!-- 工具栏 -->
            <div class="bg-gray-50 border rounded-lg p-4 mb-6">
                <div class="flex flex-wrap items-center gap-3 mb-4">
                    <button id="format-json" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="align-left" class="w-4 h-4 mr-2"></i>
                        格式化
                    </button>
                    <button id="compress-json" class="bg-purple-600 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="minimize-2" class="w-4 h-4 mr-2"></i>
                        压缩
                    </button>
                    <button id="validate-json" class="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="check-circle" class="w-4 h-4 mr-2"></i>
                        验证
                    </button>
                    <button id="escape-json" class="bg-orange-600 hover:bg-orange-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="shield" class="w-4 h-4 mr-2"></i>
                        转义
                    </button>
                    <button id="unescape-json" class="bg-teal-600 hover:bg-teal-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="unlock" class="w-4 h-4 mr-2"></i>
                        反转义
                    </button>
                    
                    <div class="ml-auto flex items-center space-x-3">
                        <button id="clear-json" class="bg-gray-200 hover:bg-gray-300 text-gray-700 font-bold py-2 px-4 rounded-lg transition duration-200">
                            清空
                        </button>
                        <button id="copy-json" class="bg-gray-200 hover:bg-gray-300 text-gray-700 font-bold py-2 px-4 rounded-lg transition duration-200">
                            复制结果
                        </button>
                        <button id="download-json" class="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200">
                            下载
                        </button>
                    </div>
                </div>
                
                <!-- 快速操作和设置 -->
                <div class="flex flex-wrap items-center gap-4 text-sm">
                    <div class="flex items-center space-x-2">
                        <label for="json-indent">缩进:</label>
                        <select id="json-indent" class="border rounded px-2 py-1 text-sm">
                            <option value="2" selected>2 空格</option>
                            <option value="4">4 空格</option>
                            <option value="tab">Tab</option>
                        </select>
                    </div>
                    <div class="flex items-center space-x-2">
                        <input type="checkbox" id="json-sort-keys" class="form-checkbox">
                        <label for="json-sort-keys">排序键名</label>
                    </div>
                    <div class="flex items-center space-x-2">
                        <input type="checkbox" id="json-decode-unicode" class="form-checkbox" checked>
                        <label for="json-decode-unicode">解码Unicode</label>
                    </div>
                    <div class="flex items-center space-x-2">
                        <input type="checkbox" id="json-syntax-highlight" class="form-checkbox" checked>
                        <label for="json-syntax-highlight">语法高亮</label>
                    </div>
                </div>
            </div>

            <!-- 错误提示 -->
            <div id="json-error" class="hidden bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-lg mb-4">
                <div class="flex items-center">
                    <i data-feather="alert-circle" class="w-5 h-5 mr-2 text-red-500"></i>
                    <div>
                        <span class="font-medium">JSON 格式错误：</span>
                        <span id="json-error-message"></span>
                    </div>
                </div>
            </div>

            <!-- 成功提示 -->
            <div id="json-success" class="hidden bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded-lg mb-4">
                <div class="flex items-center">
                    <i data-feather="check-circle" class="w-5 h-5 mr-2 text-green-500"></i>
                    <div>
                        <span class="font-medium">处理成功：</span>
                        <span id="json-success-message"></span>
                    </div>
                </div>
            </div>

            <!-- 输入区域 -->
            <div class="mb-6">
                <div class="flex items-center justify-between mb-2">
                    <label class="block text-gray-700 text-sm font-bold">
                        输入 JSON 数据
                    </label>
                    <div class="text-sm text-gray-500">
                        <span id="json-input-count">0</span> 字符 | 
                        <span id="json-input-lines">0</span> 行 |
                        <span id="json-input-size">0 B</span>
                    </div>
                </div>
                <div class="relative">
                    <textarea id="json-input" 
                        class="w-full px-4 py-3 text-gray-700 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 code-editor resize-none" 
                        rows="12" 
                        placeholder='请输入 JSON 数据，例如:
{
  "name": "DevTools",
  "version": "1.0.0",
  "features": ["JSON格式化", "压缩", "验证"],
  "settings": {
    "theme": "light",
    "autoSave": true
  }
}'></textarea>
                    <button id="paste-json" class="absolute top-3 right-3 bg-blue-500 hover:bg-blue-600 text-white px-3 py-1 rounded text-sm transition duration-200">
                        粘贴
                    </button>
                </div>
            </div>

            <!-- 输出区域 -->
            <div class="mb-6">
                <div class="flex items-center justify-between mb-2">
                    <label class="block text-gray-700 text-sm font-bold">
                        处理结果
                    </label>
                    <div class="text-sm text-gray-500">
                        <span id="json-output-count">0</span> 字符 | 
                        <span id="json-output-lines">0</span> 行 |
                        <span id="json-output-size">0 B</span> |
                        压缩率: <span id="compression-ratio" class="font-medium text-blue-600">0%</span>
                    </div>
                </div>
                <div class="relative">
                    <div id="json-output" 
                        class="w-full px-4 py-3 text-gray-700 border rounded-lg bg-gray-50 code-editor overflow-auto whitespace-pre-wrap min-h-[300px] max-h-[600px]"
                        style="font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace; font-size: 14px; line-height: 1.5;"
                        ></div>
                    <div class="absolute top-3 right-3 opacity-0 hover:opacity-100 transition-opacity duration-200">
                        <button id="select-all-output" class="bg-gray-500 hover:bg-gray-600 text-white px-3 py-1 rounded text-sm">
                            全选
                        </button>
                    </div>
                </div>
            </div>

            <!-- JSON 统计信息 -->
            <div id="json-stats" class="hidden">
                <div class="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
                    <h3 class="text-lg font-semibold text-blue-800 mb-3 flex items-center">
                        <i data-feather="bar-chart-2" class="w-5 h-5 mr-2"></i>
                        JSON 结构分析
                    </h3>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                        <div class="text-center">
                            <div class="text-2xl font-bold text-blue-600" id="stats-objects">0</div>
                            <div class="text-gray-600">对象</div>
                        </div>
                        <div class="text-center">
                            <div class="text-2xl font-bold text-green-600" id="stats-arrays">0</div>
                            <div class="text-gray-600">数组</div>
                        </div>
                        <div class="text-center">
                            <div class="text-2xl font-bold text-purple-600" id="stats-strings">0</div>
                            <div class="text-gray-600">字符串</div>
                        </div>
                        <div class="text-center">
                            <div class="text-2xl font-bold text-orange-600" id="stats-numbers">0</div>
                            <div class="text-gray-600">数字</div>
                        </div>
                    </div>
                    <div class="mt-3 text-sm text-gray-600">
                        最大深度: <span id="stats-depth" class="font-medium">0</span> |
                        总节点数: <span id="stats-size" class="font-medium">0</span> |
                        键名数量: <span id="stats-keys" class="font-medium">0</span>
                    </div>
                </div>
            </div>

            <!-- 使用提示 -->
            <div class="bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-lg p-4">
                <h3 class="text-lg font-semibold text-blue-800 mb-3 flex items-center">
                    <i data-feather="info" class="w-5 h-5 mr-2"></i>
                    功能说明
                </h3>
                <div class="grid md:grid-cols-2 gap-4 text-sm text-blue-700">
                    <div>
                        <h4 class="font-semibold mb-2">基础功能</h4>
                        <ul class="space-y-1">
                            <li>• 格式化：美化JSON结构，便于阅读</li>
                            <li>• 压缩：移除空格和换行，减少文件大小</li>
                            <li>• 验证：检查JSON语法是否正确</li>
                            <li>• 转义/反转义：处理特殊字符</li>
                        </ul>
                    </div>
                    <div>
                        <h4 class="font-semibold mb-2">高级特性</h4>
                        <ul class="space-y-1">
                            <li>• 支持大型JSON文件处理</li>
                            <li>• 实时语法高亮显示</li>
                            <li>• 结构统计分析</li>
                            <li>• 多种导出格式支持</li>
                        </ul>
                    </div>
                </div>
            </div>
        `;
    }

    static init() {
        const jsonInput = document.getElementById('json-input');
        const jsonOutput = document.getElementById('json-output');
        const formatBtn = document.getElementById('format-json');
        const compressBtn = document.getElementById('compress-json');
        const validateBtn = document.getElementById('validate-json');
        const escapeBtn = document.getElementById('escape-json');
        const unescapeBtn = document.getElementById('unescape-json');
        const clearBtn = document.getElementById('clear-json');
        const copyBtn = document.getElementById('copy-json');
        const downloadBtn = document.getElementById('download-json');
        const pasteBtn = document.getElementById('paste-json');
        const selectAllBtn = document.getElementById('select-all-output');
        
        // 设置控件
        const indentSelect = document.getElementById('json-indent');
        const sortKeysCheck = document.getElementById('json-sort-keys');
        const decodeUnicodeCheck = document.getElementById('json-decode-unicode');
        const syntaxHighlightCheck = document.getElementById('json-syntax-highlight');
        
        // 状态显示
        const statusSpan = document.getElementById('json-status');
        const errorDiv = document.getElementById('json-error');
        const successDiv = document.getElementById('json-success');
        const errorMessage = document.getElementById('json-error-message');
        const successMessage = document.getElementById('json-success-message');
        const statsDiv = document.getElementById('json-stats');

        let currentOutput = '';

        // 更新状态显示
        const updateStatus = (status) => {
            statusSpan.textContent = status;
        };

        // 显示成功消息
        const showSuccess = (message) => {
            successMessage.textContent = message;
            successDiv.classList.remove('hidden');
            errorDiv.classList.add('hidden');
            setTimeout(() => {
                successDiv.classList.add('hidden');
            }, 3000);
        };

        // 显示错误消息
        const showError = (message) => {
            errorMessage.textContent = message;
            errorDiv.classList.remove('hidden');
            successDiv.classList.add('hidden');
        };

        // 隐藏所有提示
        const hideMessages = () => {
            errorDiv.classList.add('hidden');
            successDiv.classList.add('hidden');
        };

        // 统计信息更新
        const updateStats = () => {
            const lines = jsonInput.value.split('\n').length;
            const size = new Blob([jsonInput.value]).size;
            
            document.getElementById('json-input-count').textContent = jsonInput.value.length;
            document.getElementById('json-input-lines').textContent = lines;
            document.getElementById('json-input-size').textContent = DevToolsUtils.formatFileSize(size);

            if (currentOutput) {
                const outputLines = currentOutput.split('\n').length;
                const outputSize = new Blob([currentOutput]).size;
                
                document.getElementById('json-output-count').textContent = currentOutput.length;
                document.getElementById('json-output-lines').textContent = outputLines;
                document.getElementById('json-output-size').textContent = DevToolsUtils.formatFileSize(outputSize);
                
                const ratio = jsonInput.value.length > 0 ? 
                    Math.round((1 - currentOutput.length / jsonInput.value.length) * 100) : 0;
                document.getElementById('compression-ratio').textContent = ratio + '%';
            } else {
                document.getElementById('json-output-count').textContent = '0';
                document.getElementById('json-output-lines').textContent = '0';
                document.getElementById('json-output-size').textContent = '0 B';
                document.getElementById('compression-ratio').textContent = '0%';
            }
        };

        // 更新JSON结构统计
        const updateJSONStats = (jsonString) => {
            const analysis = JSONFormatter.analyze(jsonString);
            if (analysis.success) {
                const stats = analysis.data.stats;
                document.getElementById('stats-objects').textContent = stats.objects;
                document.getElementById('stats-arrays').textContent = stats.arrays;
                document.getElementById('stats-strings').textContent = stats.strings;
                document.getElementById('stats-numbers').textContent = stats.numbers;
                document.getElementById('stats-depth').textContent = analysis.data.depth;
                document.getElementById('stats-size').textContent = analysis.data.size;
                document.getElementById('stats-keys').textContent = analysis.data.keys.size;
                statsDiv.classList.remove('hidden');
            } else {
                statsDiv.classList.add('hidden');
            }
        };

        // 输入事件监听
        jsonInput.addEventListener('input', DevToolsUtils.debounce(() => {
            updateStats();
            updateStatus('输入中...');
            
            // 实时验证
            if (jsonInput.value.trim()) {
                const result = JSONFormatter.validate(jsonInput.value);
                if (result.success) {
                    DevToolsUtils.removeStatusBorder(jsonInput);
                    updateStatus('格式正确');
                } else {
                    DevToolsUtils.addErrorBorder(jsonInput);
                    updateStatus('格式错误');
                }
            } else {
                DevToolsUtils.removeStatusBorder(jsonInput);
                updateStatus('就绪');
            }
        }, 500));

        // 格式化按钮
        formatBtn.addEventListener('click', () => {
            DevToolsUtils.addLoading(formatBtn);
            hideMessages();
            updateStatus('格式化中...');

            setTimeout(() => {
                const indent = indentSelect.value === 'tab' ? '\t' : parseInt(indentSelect.value);
                const sortKeys = sortKeysCheck.checked;
                const decodeUnicode = decodeUnicodeCheck.checked;

                const result = JSONFormatter.format(jsonInput.value, indent, sortKeys, decodeUnicode);
                if (result.success) {
                    currentOutput = result.data;

                    if (syntaxHighlightCheck.checked) {
                        jsonOutput.innerHTML = JSONFormatter.syntaxHighlight(result.data);
                    } else {
                        jsonOutput.textContent = result.data;
                    }

                    DevToolsUtils.addSuccessBorder(jsonInput);
                    showSuccess(`格式化完成，共 ${result.data.split('\n').length} 行`);
                    updateJSONStats(jsonInput.value);
                    updateStatus('格式化完成');
                } else {
                    showError(result.error);
                    DevToolsUtils.addErrorBorder(jsonInput);
                    updateStatus('格式化失败');
                }

                updateStats();
                DevToolsUtils.removeLoading(formatBtn);

                // 刷新图标
                setTimeout(() => {
                    if (typeof feather !== 'undefined') {
                        feather.replace();
                    }
                }, 100);
            }, 300);
        });

        // 压缩按钮
        compressBtn.addEventListener('click', () => {
            DevToolsUtils.addLoading(compressBtn);
            hideMessages();
            updateStatus('压缩中...');
            
            setTimeout(() => {
                const result = JSONFormatter.compress(jsonInput.value);
                if (result.success) {
                    currentOutput = result.data;
                    jsonOutput.textContent = result.data;
                    DevToolsUtils.addSuccessBorder(jsonInput);
                    
                    const savedBytes = jsonInput.value.length - result.data.length;
                    const savedPercent = Math.round((savedBytes / jsonInput.value.length) * 100);
                    showSuccess(`压缩完成，节省了 ${savedBytes} 字符 (${savedPercent}%)`);
                    updateJSONStats(jsonInput.value);
                    updateStatus('压缩完成');
                } else {
                    showError(result.error);
                    DevToolsUtils.addErrorBorder(jsonInput);
                    updateStatus('压缩失败');
                }
                
                updateStats();
                DevToolsUtils.removeLoading(compressBtn);
                
                setTimeout(() => {
                    if (typeof feather !== 'undefined') {
                        feather.replace();
                    }
                }, 100);
            }, 200);
        });

        // 验证按钮
        validateBtn.addEventListener('click', () => {
            DevToolsUtils.addLoading(validateBtn);
            hideMessages();
            updateStatus('验证中...');
            
            setTimeout(() => {
                const result = JSONFormatter.validate(jsonInput.value);
                if (result.success) {
                    DevToolsUtils.addSuccessBorder(jsonInput);
                    showSuccess('JSON 格式完全正确！');
                    updateJSONStats(jsonInput.value);
                    updateStatus('验证通过');
                } else {
                    showError(result.error);
                    DevToolsUtils.addErrorBorder(jsonInput);
                    updateStatus('验证失败');
                }
                
                DevToolsUtils.removeLoading(validateBtn);
                
                setTimeout(() => {
                    if (typeof feather !== 'undefined') {
                        feather.replace();
                    }
                }, 100);
            }, 200);
        });

        // 转义按钮
        escapeBtn.addEventListener('click', () => {
            DevToolsUtils.addLoading(escapeBtn);
            hideMessages();
            updateStatus('转义中...');
            
            setTimeout(() => {
                const result = JSONFormatter.escape(jsonInput.value);
                if (result.success) {
                    currentOutput = result.data;
                    jsonOutput.textContent = result.data;
                    showSuccess('JSON 转义完成');
                    updateStatus('转义完成');
                } else {
                    showError(result.error);
                    updateStatus('转义失败');
                }
                
                updateStats();
                DevToolsUtils.removeLoading(escapeBtn);
                
                setTimeout(() => {
                    if (typeof feather !== 'undefined') {
                        feather.replace();
                    }
                }, 100);
            }, 200);
        });

        // 反转义按钮
        unescapeBtn.addEventListener('click', () => {
            DevToolsUtils.addLoading(unescapeBtn);
            hideMessages();
            updateStatus('反转义中...');
            
            setTimeout(() => {
                const result = JSONFormatter.unescape(jsonInput.value);
                if (result.success) {
                    currentOutput = result.data;
                    jsonOutput.textContent = result.data;
                    showSuccess('JSON 反转义完成');
                    updateStatus('反转义完成');
                } else {
                    showError(result.error);
                    updateStatus('反转义失败');
                }
                
                updateStats();
                DevToolsUtils.removeLoading(unescapeBtn);
                
                setTimeout(() => {
                    if (typeof feather !== 'undefined') {
                        feather.replace();
                    }
                }, 100);
            }, 200);
        });

        // 清空按钮
        clearBtn.addEventListener('click', () => {
            jsonInput.value = '';
            jsonOutput.innerHTML = '';
            currentOutput = '';
            hideMessages();
            statsDiv.classList.add('hidden');
            DevToolsUtils.removeStatusBorder(jsonInput);
            updateStats();
            updateStatus('就绪');
        });

        // 复制按钮
        copyBtn.addEventListener('click', async () => {
            if (currentOutput) {
                await DevToolsUtils.copyToClipboard(currentOutput);
                DevToolsUtils.showToast('已复制到剪贴板！');
            } else {
                DevToolsUtils.showToast('没有可复制的内容', 'error');
            }
        });

        // 下载按钮
        downloadBtn.addEventListener('click', () => {
            if (currentOutput) {
                const filename = prompt('输入文件名:', 'formatted.json') || 'formatted.json';
                DevToolsUtils.downloadFile(currentOutput, filename, 'application/json');
                DevToolsUtils.showToast('文件下载成功！');
            } else {
                DevToolsUtils.showToast('没有可下载的内容', 'error');
            }
        });

        // 粘贴按钮
        pasteBtn.addEventListener('click', async () => {
            try {
                const text = await navigator.clipboard.readText();
                jsonInput.value = text;
                updateStats();
                DevToolsUtils.showToast('粘贴成功！');
            } catch (err) {
                DevToolsUtils.showToast('粘贴失败，请手动粘贴', 'error');
            }
        });

        // 全选输出按钮
        selectAllBtn.addEventListener('click', () => {
            const range = document.createRange();
            range.selectNodeContents(jsonOutput);
            const selection = window.getSelection();
            selection.removeAllRanges();
            selection.addRange(range);
            DevToolsUtils.showToast('已全选输出内容！');
        });

        // 语法高亮切换
        syntaxHighlightCheck.addEventListener('change', () => {
            if (currentOutput) {
                if (syntaxHighlightCheck.checked) {
                    jsonOutput.innerHTML = JSONFormatter.syntaxHighlight(currentOutput);
                } else {
                    jsonOutput.textContent = currentOutput;
                }
            }
        });

        // 初始化
        updateStats();
        updateStatus('就绪');
        
        // 刷新图标
        setTimeout(() => {
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        }, 100);
    }
};